package com.njcb.ams.store.filemonitor;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileMonitor implements Runnable {

	private static final Logger logger = LoggerFactory.getLogger(FileMonitor.class);

	private static FileMonitor fm = new FileMonitor();

	Thread monitorThread;

	private Monitor monitor;

	private String fileName;

	private String absolutefileName;

	private long initialModifiedTime = 0;
	// 属性文件所对应的属性对象变量-最后修改时间
	private long lastModifiedTime = 0;

	private FileMonitor() {
	}

	public static FileMonitor getInstance() {
		return fm;
	}

	@Override
	public void run() {
		while (true) {
			if (checkFile()) {
				monitor.operate(fileName);
				initialModifiedTime = lastModifiedTime;
			}
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				logger.error(e.getMessage(),e);
			}
		}
	}

	// 把文件加入监听
	public void add(String fileName, Monitor monitor) {
		this.monitor = monitor;
		this.fileName = fileName;
		String tempPath = Thread.currentThread().getContextClassLoader().getResource("").toString();
		this.absolutefileName = tempPath.substring(5 + File.separator.length());
		this.initialModifiedTime = new File(absolutefileName).lastModified();
		monitor.operate(fileName);
		monitorThread = new Thread(fm);
		logger.debug("加入监视文件: {}", fileName);
	}

	public void start() {
		monitorThread.start();
	}

	// 验证文件是否被修改
	private boolean checkFile() {
		try {
			lastModifiedTime = new File(absolutefileName).lastModified();
			if (lastModifiedTime == 0) {
				logger.error("{}文件不存在", new File(absolutefileName).getAbsolutePath());
			}
		} catch (Exception e) {
			logger.error("文件读取失败: {}", new File(absolutefileName).getAbsolutePath());
		}
		return lastModifiedTime > initialModifiedTime;
	}
}
